﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;

using ERPStore.Extensions;
using ERPStore.Web.Extensions;

namespace ERPStore.Web.Controllers.Controllers
{
	[System.Web.Http.Description.ApiExplorerSettings(IgnoreApi = true)]
	public class CheckoutApiController : ApiController
	{
		public CheckoutApiController(EventBrokR.IPublisher eventPublisher)
		{
			EventPublisherService = eventPublisher;
		}

		public EventBrokR.IPublisher EventPublisherService { get; set; }

		// TODO : TrackerAttribute for WebApi
		[System.Web.Http.HttpGet]
		[System.Web.Http.HttpPost]
		public void TrackGoToPaid(string cartCode, string paymentName)
		{
			var gotopaid = new Events.GoToPaidEvent() 
			{ 
				CartCode = cartCode, 
				PaymentModeName = paymentName 
			};

			EventPublisherService.PublishAsync(gotopaid);

			var ctx = this.Request.GetRequestBase();
			var request = ctx.RequestContext.HttpContext.Request;
			bool isNewVisitor = false;

			var @event = new ERPStore.Events.TrackerEvent();
			@event.ActionName = "gotopaid";
			@event.ControllerName = "checkout";
			@event.CreationDate = DateTime.Now;
			@event.Model = null;
			@event.Language = (request.UserLanguages != null && request.UserLanguages.Length > 0) ? request.UserLanguages[0] : string.Empty;
			@event.LocalPath = string.Format("/checkout/gotopaid/{0}", paymentName);
			@event.OriginalUrl = string.Format("http://{0}:80{1}", request.Url.Host.TrimEnd('/'), @event.LocalPath);
			@event.RawUrl = @event.LocalPath;
			@event.Referer = (request.UrlReferrer != null) ? request.UrlReferrer.OriginalString : string.Empty;
			@event.UserAgent = request.UserAgent;
			@event.UserHostAddress = request.UserHostAddress;
			@event.ViewName = "product";
			@event.VisitorId = ctx.RequestContext.HttpContext.GetOrCreateVisitorId(out isNewVisitor);
			@event.ResponseStatusCode = 200;
			@event.ExtendedParameters = new List<ERPStore.Models.WebParameter>();
			@event.ExtendedParameters.Add(new ERPStore.Models.WebParameter()
			{
				Type = ERPStore.Models.WebParameterType.ViewData,
				Name = "cartcode",
				Value = cartCode,
			});
			@event.ExtendedParameters.Add(new ERPStore.Models.WebParameter()
			{
				Type = ERPStore.Models.WebParameterType.ViewData,
				Name = "paymentname",
				Value = paymentName,
			});

			EventPublisherService.PublishAsync(@event);
		}

	}
}